﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace Scrt
{
    public static class Funcs
    {
        /// <summary>
        /// 获取目标Host磁盘容量字符串
        /// </summary>
        /// <returns>磁盘容量字符串</returns>
        public static string GetHostDiskVolumeStr()
        {
            string str = "";
            DriveInfo[] DrvInfo = DriveInfo.GetDrives();
            int ChrNum = DrvInfo.Length < 3 ? 16:32;
            try
            {
                foreach (var drv in DrvInfo)
                {
                    //利用十六进制链接每一个盘符的字符串
                    if (drv.TotalSize > 0)
                    {
                        str += GetMD5Hash(drv.TotalSize.ToString("X"), ChrNum);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return str;
        }
        public static string GetMatchStr(string strSrc, string pattern)
        {
            Match m = Regex.Match(strSrc, pattern, RegexOptions.IgnoreCase);
            if (m != null)
            {
                return m.Value;
            }
            return "";
        }
        /// <summary>
        /// 新建文件夹
        /// </summary>
        /// <param name="folderPath">文件夹路径</param>
        /// <returns>true：新建成功或者是文件夹存在</returns>
        public static bool CreateFolder(string folderPath)
        {
            //如果文件夹不存在，则新建
            if (!Directory.Exists(folderPath))
            {
                try
                {
                    Directory.CreateDirectory(folderPath);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 获取字符串的MD5校验值
        /// </summary>
        /// <param name="str"></param>
        /// <param name="outStrLen"></param>
        /// <returns></returns>
        public static string GetMD5Hash(string str, int outStrLen)
        {
            MD5 md5Hasher = MD5.Create();
            Byte[] DataToHash = md5Hasher.ComputeHash(Encoding.Default.GetBytes(str));
            StringBuilder sBuilder = new StringBuilder();
            switch (outStrLen)
            {
                case 16:
                    for (Int16 i = 4; i < 11; i++)
                    {
                        sBuilder.Append(DataToHash[i].ToString("X2"));
                    }
                    break;
                case 32:
                    for (Int16 i = 0; i < DataToHash.Length; i++)
                    {
                        sBuilder.Append(DataToHash[i].ToString("X2"));
                    }
                    break;
                default:
                    for (Int16 i = 0; i < DataToHash.Length; i++)
                    {
                        sBuilder.Append(DataToHash[i].ToString("X2"));
                    }
                    break;
            }
            return sBuilder.ToString();
        }
#region 字符串随机和恢复
        /// <summary>
        /// 修正位数
        /// </summary>
        private const int AmendNum = 20;
        /// <summary>
        /// 随机化字符串
        /// </summary>
        /// <param name="_str">需要随机的字符串</param>
        /// <returns>随机后的字符串</returns>
        public static string RandmStr(string _str)
        {
            string strRet = "";
            //ArrayList chrList = new ArrayList();
            Dictionary<int, string> chrDic = new Dictionary<int, string>();
            chrDic.Clear();
            for (int i = 0; i < _str.Length; i++)
            {
                chrDic.Add(i, _str.Substring(i, 1));
            }
            while (chrDic.Count > 0)
            {
                Dictionary<int, string>.KeyCollection Tmp = chrDic.Keys;
                int iTmp = Environment.TickCount % Tmp.Count;
                int keyTmp;
                string ItemTmp;
                keyTmp = Tmp.ElementAt(iTmp);//获取位置
                chrDic.TryGetValue(keyTmp, out ItemTmp);
                strRet += string.Format("{0:X3}{1}", keyTmp + AmendNum,ItemTmp);
                chrDic.Remove(keyTmp);
            }
            return strRet;
        }
        public static string RandmStr(string _str,int rndTimes)
        {
            string str = _str;
            while ((rndTimes--)>0)
            {
                str = RandmStr(str);
            }
            return str;
        }
        /// <summary>
        /// 恢复随机字符串
        /// </summary>
        /// <param name="_str">随机后的字符串</param>
        /// <returns>原始字符串</returns>
        public static string DeRandmStr(string _str)
        {
            int ArrIndex;
            int itemLen = 4;
            string strRet = "";
            string[] chrArr = new string[(int)(_str.Length / itemLen)];
            for (int i = 0; i < _str.Length; i += itemLen)
            {
                try
                {
                    ArrIndex = Convert.ToInt32(_str.Substring(i, itemLen-1),16) - AmendNum;
                    if (ArrIndex >= chrArr.GetLowerBound(0) && ArrIndex <= chrArr.GetUpperBound(0))
                    {
                        chrArr[ArrIndex] = _str.Substring(i + itemLen-1, 1);
                    }
                }
                catch
                {

                }
            }
            strRet = string.Join("", chrArr);
            chrArr = null;
            return strRet;
        }
        public static string DeRandmStr(string _str, int rndTimes)
        {
            string str = _str;
            while ((rndTimes--) > 0)
            {
                str = DeRandmStr(str);
            }
            return str;
        }
#endregion

#region 注册码保存获取

        /// <summary>
        /// 获取保存在本机的注册码
        /// </summary>
        /// <returns></returns>
        public static string GetLicense(string licensePath)
        {
            string strRet = "";
            if (File.Exists(licensePath))
            {
                using (FileStream FS = new FileStream(licensePath, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    using (BinaryReader br = new BinaryReader(FS))
                    {
                        br.BaseStream.Seek(0, SeekOrigin.Begin);
                        byte[] buffer = br.ReadBytes((int)br.BaseStream.Length);
                        strRet = Encoding.Unicode.GetString(buffer);
                        br.Close();
                        FS.Close();
                    }
                }
            }
            return DecryptDES(strRet);
        }
        /// <summary>
        /// 保存注册码
        /// </summary>
        /// <param name="license"></param>
        public static void SaveLicense(string licensePath,string license)
        {
            using (FileStream FS = new FileStream(licensePath, FileMode.Create, FileAccess.Write))
            {
                using (BinaryWriter bw = new BinaryWriter(FS))
                {
                    byte[] buffer = Encoding.Unicode.GetBytes(EncryptDES(license));
                    bw.BaseStream.Seek(0, SeekOrigin.Begin);
                    bw.Write(buffer);
                    bw.Close();
                    FS.Close();
                }
            }
        }
#endregion

#region 加密解密
        /// <summary>
        /// 加密密钥
        /// </summary>
        private const string DES_KEYS = "loveyanp";
        /// <summary>
        /// 加密密钥
        /// </summary>
        public static byte[] DESKeys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="encryptString">需要加密的字符串</param>
        /// <returns></returns>
        public static string EncryptDES(string encryptString)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(DES_KEYS.Substring(0, 8));
                byte[] rgbIV = DESKeys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="decryptString"></param>
        /// <returns></returns>
        public static string DecryptDES(string decryptString)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(DES_KEYS.Substring(0, 8));
                byte[] rgbIV = DESKeys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }

#endregion
    }
}
